//
//  HTAPICommonTools.m
//  CreditCommunity
//
//  Created by maiya on 2017/10/12.
//  Copyright © 2017年 maiya. All rights reserved.
//

#import "HTAPICommonTools.h"
#import "HTNetworking.h"

@interface HTAPICommonTools ()
// 请求次数
@property (nonatomic) NSInteger requestCount;

@end

@implementation HTAPICommonTools

#pragma mark - POST网络请求

/**
 POST 网络请求
 
 @param url 请求接口
 @param parameters 请求参数
 @param successBlock 成功回调
 @param failureBlock 失败回调
 @param netErrorBlock 无网络回调
 */
+ (void)POST:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock netError:(NetErrorBlock)netErrorBlock {
    
    HTAPICommonTools *apiTool = [[HTAPICommonTools alloc] init];
    
    [[HTNetworking sharedManager] addAPITool:apiTool];
    
    
    apiTool.url = url;
    apiTool.parameters = parameters;
    apiTool.successBlock = successBlock;
    apiTool.failureBlock = failureBlock;
    apiTool.netErrorBlock = netErrorBlock;
    
    //请求数据
    [apiTool postyData];
}


#pragma mark - GET网络请求
/**
 GET 网络请求
 
 @param url 请求接口
 @param parameters 请求参数
 @param successBlock 成功回调
 @param failureBlock 失败回调
 @param netErrorBlock 无网络回调
 */
+ (void)GET:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock netError:(NetErrorBlock)netErrorBlock {
    
    
}


- (void)postyData {
    
    // 如果此请求已经尝试过2次，则结束
    if (self.requestCount >= 2) {
        
        if (self.failureBlock) {
            self.failureBlock(@"请求失败，请稍后再试");
            [[HTNetworking sharedManager] removeAPITool:self];
        }
        return;
    }
    
    //记录请求次数
    self.requestCount++;
    __weak __typeof__(self) weakSelf = self;
    
    [[HTNetworking sharedManager] POST:self.url parameters:self.parameters success:^(id responseObject) {
        
        if (responseObject) {
            if (weakSelf.successBlock) {
                weakSelf.successBlock(responseObject);
            }
        }
        
    } failure:^(id error) {
        
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(error);
        }
    } netError:^(NSString *netError) {
        if (weakSelf.netErrorBlock) {
            weakSelf.netErrorBlock(netError);
        }
    }];
    
}

@end
